<template>
  <div class="comprehensive-table-container auto-height-container">
    <student-opbar
      :btn_arr="btn_arr"
      :config_table="config_table"
      :is_recycle="is_recycle"
      :type="1"
      :isclient="isclient"
      @add="add"
      @btn-callback="btnCallback"
      @com_del="com_del"
      @del="del"
      @fetch-data="selectData"
      @foreign-change="foreignChange"
      @get-data="getData"
      @recovery="recovery"
      @recycle="recycle"
      @upload="upload"
      @read_this_card="read_this_card"
      @read_this_card_select="read_this_card_select"
      @prints="prints"
      @printCode="printCode"
    />

    <jk-student-table
      ref="ObjTableRef"
      :config_table="config_table"
      :detail_column="detail_column"
      :detail_hide="detail_hide"
      :detail_path="detail_path"
      :detail_son_id="detail_son_id"
      :detail_st="detail_st"
      :is_recycle="is_recycle"
      :light="light"
      :list="list"
      :list-loading="listLoading"
      :show_id="show_id"
      :show_selection="show_selection"
      :status-map="statusMap"
      :isclient="isclient"
      @read_this_card="read_this_card"
      @click-field="clickField"
      @edit="edit"
      @prints="printCodeSingle"
      @get-data="getData"
    />

    <vab-pagination
      :current-page="queryForm.page"
      :page-size="queryForm.page_num"
      :page-sizes="sizes"
      :total="total"
      @current-change="currentChange"
      @size-change="pageChange"
    />
    <obj-edit-base ref="editRef" :rules="rules" :span="edit_span" :width="edit_width" @fetch-data="getData" />
  </div>
</template>

<script lang="ts" setup>
import { api_datalist, api_detail, api_getall, api_recycle, api_save } from '/@/api/obj'
import { read_card, is_client } from '/@/api/scanCard'
const dir = '/application'
const $baseConfirm = inject<any>('$baseConfirm')
const $baseMessage = inject<any>('$baseMessage')
//设置表名
const tablename = ref<any>('sport_jk_student')
//设置列表页是否显示id
const show_id = true
const show_selection = true
//设置列表页隐藏字段
const hide_list = reactive<any>([])
//设置编辑页
const edit_width = ref<any>('800px')
const edit_span = ref<any>('192px')
//设置必填项
const rules = reactive<any>({
  name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
})
const sizes = reactive<any>([10, 50, 100, 500])
//设置详情
// const detail_path = `${dir}/obj_detail`
const detail_column = 4
const detail_hide = 'store_id,custom_id' //隐藏字段，一般是列表不显示的外键
const detail_st = ref<any>('')
const detail_son_id = ref<any>('')

//设置颜色字段
const statusMap: any = {
  已入账: 'success', //绿
  待入账: 'danger', //红
  已取消: 'warning', //黄
  待签署: 'info', //灰
  入账中: '', //主题色
}
//设置浅色调默真
const light = ref<boolean>(true)

//读卡
const read_this_card = async () => {
  const { bracelet_number }: any = await read_card()
  console.log(bracelet_number)
  //根据手环号到系统中查询学生信息

  const { detail }: any = await api_detail(config_table.value.tablename, { bracelet_number: bracelet_number })
  $baseMessage(detail.name + ' ' + detail.idcard, 'success', 'hey')
  // $baseMessage(name, 'success', 'hey')
}

const read_this_card_select = async () => {
  const { bracelet_number }: any = await read_card()
  console.log(bracelet_number)
  //根据手环号到系统中查询学生信息
  queryForm.key = bracelet_number
  getData()

  // $baseMessage(name, 'success', 'hey')
}

//设置点击状态
const clickField = async (id: any, field: any, value: any) => {
  console.log(id, field, value)
  if (field == 'status') {
    if (value == '0' && 1 > 2) {
      //表示当前状态为0，为正常状态，点击提示是否下号
      $baseConfirm('您确定要审核吗', null, async () => {
        const { msg }: any = await api_save(tablename.value, { id: id, status: 1 })
        $baseMessage(msg, 'success', 'hey')
        await getData()
      })
    }
    if (value == '1' && 1 > 2) {
      //表示当前状态为1，为下号状态，点击提示是否上号
      $baseConfirm('您确定要取消审核吗', null, async () => {
        const { msg }: any = await api_save(tablename.value, { id: id, status: 0 })
        $baseMessage(msg, 'success', 'hey')
        await getData()
      })
    }
  }
}
//设置操作条中的按钮
// const btn_arr = [{ name: '审核', method: 'check', type: 'success' }]
//设置点击操作条中的方法
const btnCallback = async (method: any) => {
  console.log(method)
  console.log(ObjTableRef.value.selectRows) //选中的行
}
const name = tablename.value
console.log(name)
defineOptions({
  name: `${dir}Obj`,
})
const route: any = useRoute()
//通用变量
const editRef = ref<any>(null)
const ObjTableRef = ref<any>(null)
const list = ref<any>([])
const listLoading = ref<boolean>(true)
const total = ref<any>(0)

const queryForm = reactive<any>({
  page: 1,
  page_num: 10,
})
const config_table = ref<any>({})
const login_log = ref<any>({})
const is_recycle = ref<boolean>(false) //当前是否是回收站
const isclient = ref<boolean>(false) //当前是否是客户端
//自定义变量

//自定义方法

//通用获取数据
const getData = async () => {
  listLoading.value = true
  api_datalist(tablename.value, queryForm).then((res: any) => {
    if (res) {
      is_recycle.value = false
      //隐藏掉隐藏的字段
      const list_show = res.config_table.list_show
      for (let i = 0; i < list_show.length; i++) {
        for (let y = 0; y < hide_list.length; y++) {
          if (list_show[i] == hide_list[y]) {
            list_show[i] = ''
          }
        }
      }
      config_table.value = res.config_table
      login_log.value = res.login_log
      list.value = res.datalist
      total.value = res.num
      listLoading.value = false
      handleMeta('DynamicMeta', { title: res.config_table.table_comment })
    }
  })
}

//设置动态标题
import { ElLoading } from 'element-plus'
import { api_upload } from '/@/api/obj'
import { useRoutesStore } from '/@/store/modules/routes'
import { useTabsStore } from '/@/store/modules/tabs'
import getPageTitle from '/@/utils/pageTitle'
const tabsStore = useTabsStore()
const routesStore = useRoutesStore()
const { changeActiveMenu, changeMenuMeta } = routesStore
const { changeTabsMeta } = tabsStore

const handleMeta = (name: any, meta: { title: string }) => {
  if (meta.title) useTitle().value = getPageTitle(meta.title)
  changeMenuMeta({ name, meta })
  changeTabsMeta({ name, meta })
}
const handleActiveMenu = (activeMenu: string) => {
  console.log(activeMenu)
  changeActiveMenu(activeMenu)
}

//通用外键变更
const foreignChange = ($event: any, model: any, field: any) => {
  console.log(model, $event, field)
  if (config_table.value.foreign_field[model] && config_table.value.foreign_field[model].next) {
    //表示有级联，去查对应表的数据
    const table = config_table.value.foreign_field[model].next
    getForeignList(table, $event, field)
  }
}
//通用根据外键ID获取对应数据
const getForeignList = (table: any, event: any, field: any) => {
  console.log(table, event, field)
  let search: any = {}
  search[field] = parseInt(event) > 0 ? parseInt(event) : 0
  search = JSON.stringify(search)
  api_getall(table, {
    search: search,
  }).then((res) => {
    //获取出来的结果赋值给对应级联表中
    // flist[`${table}_T_${config_table.value.foreign[table].field}`] = res.datalist

    //获取出来的结果赋值给对应级联表中
    const flist = config_table.value.foreign_list
    search = JSON.parse(search)
    for (const key in flist) {
      if (key.startsWith(`${table}_T_`)) {
        //赋值筛选后的数据
        flist[`${key}`] = res.datalist
        //清空级联下级的值
        //queryForm.search[key.replace(table + '_T_', '')] = ''
      }
    }
  })
}
//通用进入回收站
const recycle = async () => {
  listLoading.value = true
  api_recycle(tablename.value, queryForm).then((res: any) => {
    if (res) {
      is_recycle.value = true
      config_table.value = res.config_table
      list.value = res.datalist
      total.value = res.num
      listLoading.value = false
    }
  })
}
//通用查询
const selectData = (data: any) => {
  Object.assign(queryForm, data)
  getData()
}
//通用普通删除(用于选择删除)
const del = (row: any) => {
  ObjTableRef.value.del(row)
}
//通用彻底删除
const com_del = (row: any) => {
  ObjTableRef.value.com_del(row)
}
//通用恢复操作
const recovery = (row: any) => {
  ObjTableRef.value.recovery(row)
}
//上传数据
const upload = () => {
  console.log(queryForm)
  //表示当前状态为0，为正常状态，点击提示是否下号
  $baseConfirm('您确定要上传数据吗', null, async () => {
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const { msg }: any = await api_upload(config_table.value.tablename, queryForm)
    $baseMessage(msg, 'success', 'hey')
    loading.close()
  })
}
//通用添加
const add = () => {
  editRef.value.showEdit(config_table.value)
}
//通用编辑
const edit = (row = {}) => {
  editRef.value.showEdit(row)
}
//通用每页数量修改
const pageChange = (value: number) => {
  queryForm.page = 1
  queryForm.page_num = value
  getData()
}
//通用翻页
const currentChange = (value: number) => {
  queryForm.page = value
  getData()
}

//打印
// import { ElMessageBox } from 'element-plus'
import VabPrint from '/@/plugins/VabPrint'
import { getStudentsPrints,getStudentsPrintCode,getStudentsPrintCodeSingle } from '/@/api/jkDataScreen'
const printCodeSingle = async (formdata: any) => {
  console.log('printCodeSingle' , formdata)
  const { data } = await getStudentsPrintCodeSingle({id:formdata.detail.id})
  console.log(data.students)


  let content = `<style>
  .student-table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed; /* 新增固定布局 */
  }
  .student-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;
    min-height: 200px; /* 保证最小高度 */
    border: 0px solid #ddd; /* 添加边框方便观察 */
  }
  .student-card img {
    width: 100px;
    height: 100px; /* 固定图片高度 */
    object-fit: contain; /* 保持图片比例 */
    margin-bottom: 12px;
  }
</style>`;

content += '<table class="student-table">';

// 分组逻辑加强
const groupSize = 1;
const students = data.students;
const totalRows = Math.ceil(students.length / groupSize);

for (let row = 0; row < totalRows; row++) {
  content += '<tr>';
  
  const start = row * groupSize;
  const end = start + groupSize;
  const group = students.slice(start, end);

  group.forEach((student: { qrcode: any; name: any; sport_school_name: any; sport_grade_name: any; sport_jk_class_name: any }) => {
    content += `
      <td style="vertical-align: top;">
        <div class="student-card">
          <img src="${student.qrcode}">
          <div><strong>${student.name}</strong></div>
          <div style="font-size:10px">${student.sport_school_name}</div>
          <div style="font-size:10px">${student.sport_grade_name}${student.sport_jk_class_name}</div>
        </div>
      </td>
    `;
  });

  // 补全单元格并添加占位高度
  if (group.length < groupSize) {
    for (let j = 0; j < groupSize - group.length; j++) {
      content += '<td style="vertical-align: top;"><div class="student-card" style="visibility: hidden;">&nbsp;</div></td>';
    }
  }
  
  content += '</tr>';
}

content += '</table>';


  VabPrint(content)

}
const printCode = async (formdata: any) => {
  console.log('prints' + formdata)
  const { data } = await getStudentsPrintCode(formdata)
  console.log(data.students)

  // let content = '<style>table,table tr th, table tr td {border-collapse: collapse; }</style>'
  // content += '<table style="width:100%;text-align: center;" border=0>'
  // content += '<tr>'
  // content += '<th colspan="5">'
  // content += data.title
  // content += '</th>'
  // content += '<tr>'

  // content +=
  //   '<tr><td>二维码</td><td>姓名</td><td>学籍号</td><td>学校</td><td>班级</td><tr>'

  // for (let i = 0; i < data.students.length; i++) {
  //   content += '<tr>'
  //   content += '<td style="width:20%"><img src="' + data.students[i].qrcode + '" width="100px"></td>'
  //   content += '<td style="width:20%">' + data.students[i].name + '</td>'
  //   content += '<td>' + data.students[i].student_code + '</td>'
  //   content += '<td>' + data.students[i].sport_school_name + '</td>'
  //   content += '<td>' + data.students[i].sport_grade_name + data.students[i].sport_jk_class_name + '</td>'

    

  //   content += '<tr>'
  // }

  // content += '</table>'

  let content = `<style>
  @media print {
    @page {
      size: A4;
      margin: 5mm; /* 减小页面边距 */
    }
  }
  .student-table {
    width: 96.6%;
    border-collapse: collapse;
    table-layout: fixed;
    font-size: 8px; /* 整体调小字体 */
  }
  .student-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0px; /* 减小内边距 */
    min-height: 116px; /* 调小最小高度 */
    border: 0px solid #ddd;
    page-break-inside: avoid; /* 防止分页截断 */
  }
  .student-card img {
    width: 70px;   /* 调小二维码尺寸 */
    height: 70px;  /* 保持正方形比例 */
    object-fit: contain;
    margin-bottom: 0px; /* 减小图片下边距 */
  }
  .student-card div {
    margin: 2px 0; /* 减小文字间距 */
    line-height: 0.8; /* 紧凑行高 */
    text-align: center;
  }
</style>`;

content += '<table class="student-table">';

const groupSize = 7; // 每行7个
const students = data.students;
const totalRows = Math.ceil(students.length / groupSize);

for (let row = 0; row < totalRows; row++) {
  content += '<tr style="height: 14.28%;">'; // 固定行高
  
  const start = row * groupSize;
  const end = start + groupSize;
  const group = students.slice(start, end);

  group.forEach(student => {
    content += `
      <td width="14.28%"> <!-- 固定列宽 -->
        <div class="student-card">
          <img src="${student.qrcode}">
          <div><strong style="font-size:10px">${student.name}</strong></div>
          <div>${student.sport_school_name}</div>
          <div>${student.sport_grade_name}${student.sport_jk_class_name}</div>
        </div>
      </td>
    `;
  });

  // 补全空单元格
  if (group.length < groupSize) {
    for (let j = 0; j < groupSize - group.length; j++) {
      content += '<td><div class="student-card" style="visibility: hidden;">&nbsp;</div></td>';
    }
  }
  
  content += '</tr>';
}

content += '</table>';

VabPrint(content);

  // ElMessageBox.prompt('', '打印预览', {
  //   inputType: 'textarea',
  //   inputValue: content,
  //   inputErrorMessage: 'Invalid Email',
  //   confirmButtonText: '打印',
  //   draggable: true,
  // })
  //   .then(({ value }) => {
  //     console.log(value)
  //     VabPrint(value)
  //   })
  //   .catch(() => {})
}
const prints = async (formdata: any) => {
  console.log('prints' + formdata)
  const { data } = await getStudentsPrints(formdata)
  console.log(data.students)

  let content = '<style>table,table tr th, table tr td {border-collapse: collapse; }</style>'
  content += '<table style="width:100%;" border=1 >'
  content += '<tr>'
  content += '<th colspan="17">'
  content += data.title
  content += '</th>'
  content += '<tr>'

  content +=
    '<tr><td>姓名</td><!--<td>学籍号</td>--><td>总分</td><td>身高</td><td>体重</td><td>体重指数</td><td>肺活量</td><td>50米跑</td><td>坐位体前屈</td><td>1分钟跳绳</td><td>1分钟仰卧起坐</td><td>引体向上(男)</td><td>1分钟仰卧起坐(女)</td><td>立定跳远</td><td>50米×8往返跑</td><td>1000米跑(男)</td><td>800米跑(女)</td><tr>'

  for (let i = 0; i < data.students.length; i++) {
    content += '<tr>'
    content += '<td style="width:6%">' + data.students[i].achievement.name + '</td>'
    // content += '<td>' + data.students[i].student_code + '</td>'
    content += '<td>' + data.students[i].score + '</td>'
    content += '<td>' + data.students[i].height + '</td>'
    content += '<td>' + data.students[i].weight + '</td>'
    content += '<td>' + data.students[i].bmi + '(' + data.students[i].achievement.bmi + ')' + '</td>'
    content += '<td>' + data.students[i].lung_capacity + '(' + data.students[i].achievement.lung_capacity + ')' + '</td>'

    content += '<td>' + data.students[i].run_50 + '(' + data.students[i].achievement.run_50 + ')' + '</td>'
    content += '<td>' + data.students[i].sit_and_reach + '(' + data.students[i].achievement.sit_and_reach + ')' + '</td>'
    content += '<td>' + data.students[i].jump_rope + '(' + data.students[i].achievement.jump_rope + ')' + '</td>'
    content += '<td>' + data.students[i].sit_ups + '(' + data.students[i].achievement.sit_ups + ')' + '</td>'
    content += '<td>' + data.students[i].pull_ups + '(' + data.students[i].achievement.pull_ups + ')' + '</td>'

    content += '<td>' + data.students[i].sit_ups_female + '(' + data.students[i].achievement.sit_ups_female + ')' + '</td>'
    content += '<td>' + data.students[i].jump_long + '(' + data.students[i].achievement.jump_long + ')' + '</td>'
    content += '<td>' + data.students[i].run_50_8 + '(' + data.students[i].achievement.run_50_8 + ')' + '</td>'
    content += '<td>' + data.students[i].run_1000 + '(' + data.students[i].achievement.run_1000 + ')' + '</td>'
    content += '<td>' + data.students[i].run_800 + '(' + data.students[i].achievement.run_800 + ')' + '</td>'

    content += '<tr>'
  }

  content += '</table>'
  //获取所有学生
  // api_getStudents（

  VabPrint(content)

  // ElMessageBox.prompt('', '打印预览', {
  //   inputType: 'textarea',
  //   inputValue: content,
  //   inputErrorMessage: 'Invalid Email',
  //   confirmButtonText: '打印',
  //   draggable: true,
  // })
  //   .then(({ value }) => {
  //     console.log(value)
  //     VabPrint(value)
  //   })
  //   .catch(() => {})
}

//通用加载前
onMounted(() => {
  getData()
})

onBeforeMount(() => {
  let i = true
  //如果参数是add大于0时，自动弹出添加
  console.log(`${route.query.t}`)

  let param = ''
  let first = true

  if (`${route.query.t}` != 'undefined') {
    console.log('有t')
    tablename.value = `${route.query.t}`
    param += first ? '?' + `t=${tablename.value}` : '&' + `t=${tablename.value}`
    console.log(param)
    first = false
  }

  if (`${route.query.edit_span}` != 'undefined') {
    edit_span.value = `${route.query.edit_span}`
    param += first ? '?' + `edit_span=${edit_span.value}` : '&' + `edit_span=${edit_span.value}`
    first = false
  }

  if (`${route.query.edit_width}` != 'undefined') {
    edit_width.value = `${route.query.edit_width}`
    param += first ? '?' + `edit_width=${edit_width.value}` : '&' + `edit_width=${edit_width.value}`
    first = false
  }

  if (`${route.query.st}` != 'undefined') {
    detail_st.value = `${route.query.st}`
    param += first ? '?' + `st=${detail_st.value}` : '&' + `st=${detail_st.value}`
    first = false
  }

  if (`${route.query.son_id}` != 'undefined') {
    detail_son_id.value = `${route.query.son_id}`
    param += first ? '?' + `son_id=${detail_son_id.value}` : '&' + `son_id=${detail_son_id.value}`
    first = false
  }

  const acmenu = `${dir}/objOri${param}`
  console.log('acmenu', `${acmenu}`)
  handleActiveMenu(`${acmenu}`)

  //如果参数是add大于0时，自动弹出添加
  if (parseInt(`${route.query.add}`) > 0) {
    setInterval(function () {
      if (i && config_table.value) {
        add()
        i = false
      }
    }, 1000)
  }
  //如果参数是edit大于0时，自动弹出编辑
  if (parseInt(`${route.query.edit}`) > 0) {
    setInterval(function () {
      if (i && config_table.value) {
        api_detail(config_table.value.tablename, { id: parseInt(`${route.query.edit}`) }).then((res: any) => {
          if (res.detail) {
            edit(res)
          }
          i = false
        })
      }
    }, 1000)
  }

  isclient.value = is_client()
})
</script>
